﻿using BlogSystem.Mediator.Handler;

namespace BlogSystem.Mediator.Mediator;

/// <summary>
/// 实现中介者 接口
/// </summary>
public class Mediator : IMediator
{
    private readonly Dictionary<Type, List<object>> _handlers;

    public Mediator()
    {
        _handlers = new Dictionary<Type, List<object>>();
    }

    public async Task PublishAsync<TNotification>(TNotification notification) where TNotification : INotification
    {
        var notificationType = typeof(TNotification);
        if (_handlers.ContainsKey(notificationType))
        {
            foreach (var handler in _handlers[notificationType])
            {
                if (handler is INotificationHandler<TNotification> concreteHandler)
                {
                    await concreteHandler.Handle(notification);
                }
            }
        }
    }

    public async Task SubscribeAsync<TNotification>(INotificationHandler<TNotification> handler) where TNotification : INotification
    {
        var notificationType = typeof(TNotification);
        if (!_handlers.ContainsKey(notificationType))
        {
            _handlers[notificationType] = new List<object>();
        }
        _handlers[notificationType].Add(handler);
    }

    public async Task UnsubscribeAsync<TNotification>(INotificationHandler<TNotification> handler) where TNotification : INotification
    {
        var notificationType = typeof(TNotification);
        if (_handlers.ContainsKey(notificationType))
        {
            _handlers[notificationType].Remove(handler);
        }
    }
}
